package cn.tinlan.shopcoin.app.mine.set;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONObject;

import butterknife.BindView;
import cn.tinlan.shopcoin.MainActivity;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ConvertUtil;
import cn.tinlan.shopcoin.Utils.PayUtils;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.login.LoginActivity;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import cn.tinlan.shopcoin.widget.pay.PayListenerUtils;
import cn.tinlan.shopcoin.widget.pay.PayResultListener;

/**
 * Created by Mortimer on 2018/12/11. 18:07
 * 佛祖🙏，永无bug。
 */
public class MineWalletMoneyActivity extends BaseActivity implements View.OnClickListener, PayResultListener{

    @BindView(R.id.wallet_money_title1)
    TitleBar wallet_money_title;
    @BindView(R.id.wallet_money_tv)
    TextView wallet_money_tv;
    @BindView(R.id.wallet_money_et)
    EditText wallet_money_et;
    @BindView(R.id.wallet_alipay_img)
    ImageView wallet_alipay_img;
    @BindView(R.id.wallet_wx_img)
    ImageView wallet_wx_img;

    @BindView(R.id.wallet_notice_tv)
    TextView wallet_notice_tv;

    @BindView(R.id.wallet_poundage_content)
    View wallet_poundage_content;
    @BindView(R.id.wallet_cash_poundage)
    TextView wallet_cash_poundage;
    @BindView(R.id.wallet_min_poundage)
    TextView wallet_min_poundage;



    @BindView(R.id.wallet_pay_methond)
    TextView wallet_paymethond_view;
    @BindView(R.id.wallet_money_alipay)
    View wallet_alipay_view;
    @BindView(R.id.wallet_money_wx)
    View wallet_wx_view;

    @BindView(R.id.wallet_money_btn)
    Button wallet_money_btn;

    public static final int RESULT_CODE = 1807;
    private int pay_type = 1;
    private boolean isBtnSelect = false;
    private  int money_type = 1;

    private int tempMoney = 0;
    private boolean tempMoneyFinish = false;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mine_walletmoney;
    }

    @Override
    public void initView() {
        super.initView();
        drawableDefaultBar();
        initTitleBar();
        bindViewClickEvents();
    }

    @Override
    public void initData() {
        super.initData();
        PayListenerUtils.getInstance(MineWalletMoneyActivity.this).addListener(MineWalletMoneyActivity.this);
    }

    private void initTitleBar() {

        String title = getIntent().getStringExtra("title");
        if (title.equals("recharge")) {
            wallet_money_title.setTitle("充值");
            wallet_money_btn.setText("充值");
            wallet_poundage_content.setVisibility(View.GONE);
//            wallet_notice_tv.setVisibility(View.INVISIBLE);
            configMinRecharge(1);
            money_type = 1;
        }else {
            wallet_money_title.setTitle("提现");
            wallet_money_btn.setText("提现");
            wallet_paymethond_view.setVisibility(View.GONE);
            wallet_alipay_view.setVisibility(View.GONE);
            wallet_wx_view.setVisibility(View.GONE);
            configMinRecharge(2);
            money_type = 2;

        }

        wallet_money_title.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });

    }

    private void bindViewClickEvents() {

        wallet_money_btn.setOnClickListener(this);


        if (money_type == 1){
            wallet_alipay_img.setOnClickListener(this);
            wallet_wx_img.setOnClickListener(this);
            wallet_alipay_img.setSelected(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wallet_alipay_img:
                if (wallet_alipay_img.isSelected())return;
                wallet_alipay_img.setSelected(!wallet_alipay_img.isSelected());
                pay_type = 1;
                if (wallet_wx_img.isSelected()) {
                    wallet_wx_img.setImageResource(0);
                    wallet_alipay_img.setImageResource(R.drawable.pay_methond_select);
                    wallet_wx_img.setSelected(false);
                }
                break;
            case R.id.wallet_wx_img:
                if (wallet_wx_img.isSelected())return;
                wallet_wx_img.setSelected(!wallet_wx_img.isSelected());
                pay_type = 2;
                if (wallet_alipay_img.isSelected()) {
                    wallet_wx_img.setImageResource(R.drawable.pay_methond_select);
                    wallet_alipay_img.setImageResource(0);
                    wallet_alipay_img.setSelected(false);
                }
                break;
            case R.id.wallet_money_btn:

//                Intent recharge = new Intent(MineWalletMoneyActivity.this, MainActivity.class);
////                recharge.putExtra("currentFragment",2);
//
////               recharge.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                recharge.putExtra("currentFragment",2);
//                recharge.putExtra("test","2");
//               startActivity(recharge);
                if (money_type == 1) {
                    toRecharge();
                }else {
                    toWithdraw();
                }

                break;

        }
    }




    private void toRecharge() {


        String money = wallet_money_et.getText().toString();
        if (!ConvertUtil.isNumber(money)){
            ToastUtils.show("输入非法类型，请重新输入");
            wallet_money_et.setText("");
            return;
        }

        float currentMoney = Float.parseFloat(money);
        if (currentMoney < tempMoney || tempMoneyFinish == false) {
            ToastUtils.show("您必须充值大于等于"+tempMoney);
            return;
        }

        if (isBtnSelect) return;
        isBtnSelect = true;

        EasyHttp.post(Constants.UserRecharge)
                .params("money",money)
                .params("user_id", SPUtils.getUserID(MineWalletMoneyActivity.this))
                .params("pay_type",""+pay_type)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        isBtnSelect = false;
                    }

                    @Override
                    public void onSuccess(String s) {
                        isBtnSelect = false;
                        try {
                            JSONObject json = new JSONObject(s);
                            String result = json.get("data").toString();

                            if (pay_type == 1) {
                                PayUtils.getInstance(MineWalletMoneyActivity.this)
                                        .pay(PayUtils.PAY_TYPE_ALI,result);
                            }else {
                                ToastUtils.show("微信暂不支持，敬请期待");
//                                PayUtils.getInstance(MineWalletMoneyActivity.this)
//                                        .pay(PayUtils.PAY_TYPE_WX,result);
                            }



                        }catch (Exception e) {
                            e.printStackTrace();
                        }



                    }
                }) {
                });
    }


    private void  toWithdraw() {
        String money = wallet_money_et.getText().toString();
        if (!ConvertUtil.isNumber(money)){
            ToastUtils.show("输入非法类型，请重新输入");
            wallet_money_et.setText("");
            return;
        }

        float currentMoney = Float.parseFloat(money);
        if (currentMoney < tempMoney || tempMoneyFinish == false) {
            ToastUtils.show("您提现必须大于等于"+tempMoney);
            return;
        }
        if (isBtnSelect) return;
        isBtnSelect = true;

//        ToastUtils.show("功能暂未开启");
        EasyHttp.post(Constants.UserWithRaw)
                .params("money",money)
                .params("user_id", SPUtils.getUserID(MineWalletMoneyActivity.this))
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        isBtnSelect = false;
                    }

                    @Override
                    public void onSuccess(String s) {
                        isBtnSelect = false;
                        try {
                            JSONObject json = new JSONObject(s);
                            String result = json.get("data").toString();
                            ToastUtils.show(result);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                }) {
                });
    }


    private void configMinRecharge(final int urlType) {

        String url = "";
        if (urlType == 1) {
            url = Constants.ConfigMinRecharge;
        }else {
            url = Constants.ConfigMinCash;
        }

        EasyHttp.get(url)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        String code = jsonObject.getString("code");
                        tempMoneyFinish = true;
                        if (code.equals("1")){


                            if (urlType == 1) {
                                tempMoney = Integer.parseInt(jsonObject.getString("data"));
                                wallet_notice_tv.setText("单笔最小充值金额："+jsonObject.getString("data"));
                            }else {
                                JSONObject data = jsonObject.getJSONObject("data");
                                String min_cash = data.getString("min_cash");
                                tempMoney =Integer.parseInt(min_cash);
                                String cash_poundage = data.getString("cash_poundage");

                                float tempCash = Float.parseFloat(cash_poundage);
                                tempCash = tempCash * 100;

                                String min_poundage = data.getString("min_poundage");
                                wallet_notice_tv.setText("单笔最小提现金额："+min_cash);
                                wallet_cash_poundage.setText("提现最小收取比率："+tempCash+"%");
                                wallet_min_poundage.setText("提现最低手续费："+min_poundage);
                            }

                        }else {
                            ToastUtils.show(jsonObject.getString("data"));
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }

                    }
                }) {
                });
    }


    @Override
    public void onPaySuccess() {
        Log.d("pay------>>","success");
    }

    @Override
    public void onPayError() {
        Log.d("pay------>>","error");

    }

    @Override
    public void onPayCancel() {
        Log.d("pay------>>","cancel");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PayListenerUtils.getInstance(MineWalletMoneyActivity.this).removeListener(MineWalletMoneyActivity.this);
    }





    //实现点击屏幕收起键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction()==MotionEvent.ACTION_DOWN){
            View v=getCurrentFocus();
            boolean  hideInputResult =isShouldHideInput(v,ev);
            Log.v("hideInputResult","zzz-->>"+hideInputResult);
            if(hideInputResult){
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) MineWalletMoneyActivity.this
                        .getSystemService(Activity.INPUT_METHOD_SERVICE);
                if(v != null){
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            //之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标！！！
//            Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
//            Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
